﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using TestMySqlConnetPoll;
using System.Threading;
using System.Collections;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils.Drawing;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.Utils;
using DevExpress.XtraGrid.Columns;
using DevExpress.Data;
using DevExpress.Skins;
using View.History;
using View.Common;

namespace View.Alarm
{
   
    /// <summary>
    /// 实时报警
    /// </summary>
    public partial class FrmRealAlarm : DevExpress.XtraEditors.XtraForm
    {
        private BindingList<HistroyAlarmObj> source = new BindingList<HistroyAlarmObj>();
        private GridCheckMarksSelection selection;
        private int alarmIndex1;
        private int alarmIndex2;
        private int alarmIndex3;
        private int alarmIndex4;
        

        public ArrayList _selection = new ArrayList();

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmRealAlarm()
        {
            //DevExpress.Utils.AppearanceObject.DefaultFont = new System.Drawing.Font("宋体", 9); //解决输出PDF乱码
           
            InitializeComponent();
            timer1.Enabled = true;
            
            col_level.Group();
            
            this.DevDataGrid.DataSourceChanged +=DevDataGrid_DataSourceChanged;
                                   
        }

        void gridView1_CustomColumnSort(object sender, CustomColumnSortEventArgs e)
        {
            //throw new NotImplementedException();
        }

        
        void DevDataGrid_DataSourceChanged(object sender, EventArgs e)
        {
            //selection = new GridCheckMarksSelection(gridView1);
            //selection.CheckMarkColumn.VisibleIndex = 0;
            //selection.CheckMarkColumn.Width = 30;
            //selection.CheckMarkColumn.OptionsColumn.AllowEdit = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //selection = new GridCheckMarksSelection(gridView1);
            //selection.CheckMarkColumn.VisibleIndex = 0;
            //selection.CheckMarkColumn.Width = 30;
            source = UtilityFunc.source;
            this.DevDataGrid.DataSource = source; 
            if(!UtilityFunc.bestfit)
            {
                UtilityFunc.bestfit = true;
                this.gridView1.BestFitColumns();
            }
            //SetAlarmInfo();
            //this.DevDataGrid.RefreshDataSource();
        }

        /// <summary>
        /// 报警处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAlarmC_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (childRows != null && childRows.Length > 0)
            {
                FrmUserConFrimAlarm frm = new FrmUserConFrimAlarm();
                frm.list = this._selection;

                int[] rowHandelArr = new int[childRows.Length];
                childRows.CopyTo(rowHandelArr, 0);

                DialogResult result = frm.ShowDialog();
                int delCount = 0;
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    int rowHandel = 0;
                    for (int i = 0; i < rowHandelArr.Length; i++)
                    {
                        if (rowHandelArr[i] >=0)
                        {
                            rowHandel = rowHandelArr[i] - delCount; 
                            this.gridView1.DeleteRow(rowHandel);
                            delCount ++;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private int[] childRows = null;
        private void gridView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._selection.Clear();
            childRows = this.gridView1.GetSelectedRows();

            for(int i =0;i<childRows.Length;i++)
            {
                if (childRows[i] < 0) continue;
                object obj = this.gridView1.GetRow(childRows[i]);

                if(obj!= null)
                    this._selection.Add(obj);
            }
        }

        public List<int> GetChildRowsHandles(GridView view, int groupRowHandle)
        {
            List<int> childRows = new List<int>();

            if (!view.IsGroupRow(groupRowHandle))
            {
                return childRows;
            }

            int childCount = view.GetChildRowCount(groupRowHandle);
            for (int i = 0; i < childCount; i++)
            {
                int childHandle = view.GetChildRowHandle(groupRowHandle, i);
                if (view.IsDataRow(childHandle))
                {
                    if (!childRows.Contains(childHandle))
                        childRows.Add(childHandle);
                }
            }

            return childRows;
        }

        struct LevelStruct
        {
            public string levelStr;
            public int StartNo;
        }
        List<LevelStruct> LevelList = new List<LevelStruct>();
        
        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {                            
                    HistroyAlarmObj obj = this.gridView1.GetRow(e.RowHandle) as HistroyAlarmObj;
                    string tmpLevel = obj.AlarmLevel;

                    if (LevelList.Exists(x => x.levelStr == tmpLevel)) { }
                    else
                    {
                        LevelStruct tt = new LevelStruct();
                        tt.levelStr = tmpLevel;
                        tt.StartNo = e.RowHandle;
                        LevelList.Add(tt);
                    }
                    int activeNo = 0;
                    for (int i = 0; i < LevelList.Count; i++)
                    {
                        if (LevelList[i].levelStr == tmpLevel)
                        {
                            activeNo = e.RowHandle - LevelList[i].StartNo;
                        }
                    }
                    e.Info.DisplayText = (Interlocked.Increment(ref activeNo)).ToString();                    
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {                    
                    ////e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    ////e.Info.DisplayText = "G" + e.RowHandle.ToString();                    
                }
            }
        }

        private void gridView1_BeforePrintRow(object sender, DevExpress.XtraGrid.Views.Printing.CancelPrintRowEventArgs e)
        {
            //string groupName = this.gridView1.gr
        }

        private void gridView1_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            GridGroupRowInfo GridGroupRowInfo = e.Info as GridGroupRowInfo;
            string s = GridGroupRowInfo.GroupValueText;
            string gtext = s;
            if (UtilityFunc.sourceLevel.ContainsKey(s))
            {
                GridGroupRowInfo.GroupText = "";
                GridGroupRowInfo.GroupText = gtext + string.Format("  共计:{0}条", UtilityFunc.sourceLevel[s].Count);
            }
        }
    }

    public class AlarmType
    {
        public string name { get; set; }
        public string type { get; set; }
        public string detail { get; set; }
        public string alarmLevel { get; set; }
        public int alarmCount { get; set; }
    }

    public class GridCheckMarksSelection
    {

        public event EventHandler SelectionChanged;

        protected GridView _view;
        public ArrayList _selection;
        private GridColumn _column;
        private RepositoryItemCheckEdit _edit;

        public GridView View
        {
            get { return _view; }
            set
            {
                if (_view == value)
                    return;
                if (_view != null)
                    Detach();
                _view = value;
                Attach();
            }
        }

        public GridColumn CheckMarkColumn { get { return _column; } }
        public int SelectedCount { get { return _selection.Count; } }

        public GridCheckMarksSelection()
        {
            _selection = new ArrayList();
        }

        public GridCheckMarksSelection(GridView view)
            : this()
        {
            this.View = view;
        }

        protected virtual void Attach()
        {
            if (View == null)
                return;
            _selection.Clear();
            _view = View;
            _edit = View.GridControl.RepositoryItems.Add("CheckEdit")
                as RepositoryItemCheckEdit;
            _edit.EditValueChanged += edit_EditValueChanged;
            _column = View.Columns.Insert(0);
            _column.OptionsColumn.AllowSort = DefaultBoolean.False;
            _column.VisibleIndex = int.MinValue;
            _column.FieldName = "CheckMarkSelection";
            _column.Caption = "Mark";
            _column.OptionsColumn.ShowCaption = false;
            _column.UnboundType = UnboundColumnType.Boolean;
            _column.ColumnEdit = _edit;


            View.CustomDrawColumnHeader += View_CustomDrawColumnHeader;
            View.CustomDrawGroupRow += View_CustomDrawGroupRow;
            View.CustomUnboundColumnData += view_CustomUnboundColumnData;

            View.MouseUp += view_MouseUp;

            

        }

        protected virtual void Detach()
        {
            if (_view == null)
                return;
            if (_column != null)
                _column.Dispose();
            if (_edit != null)
            {
                _view.GridControl.RepositoryItems.Remove(_edit);
                _edit.Dispose();
            }
            _view.CustomDrawColumnHeader -= View_CustomDrawColumnHeader;
            _view.CustomDrawGroupRow -= View_CustomDrawGroupRow;
            _view.CustomUnboundColumnData -= view_CustomUnboundColumnData;
            _view.MouseDown -= view_MouseUp;
            _view = null;
        }

        protected virtual void OnSelectionChanged(EventArgs e)
        {
            if (SelectionChanged != null)
                SelectionChanged(this, e);
        }

        protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
        {
            var info = _edit.CreateViewInfo() as CheckEditViewInfo;
            var painter = _edit.CreatePainter() as CheckEditPainter;
            ControlGraphicsInfoArgs args;
            info.EditValue = Checked;
            info.Bounds = r;
            info.CalcViewInfo(g);
            args = new ControlGraphicsInfoArgs(info, new GraphicsCache(g), r);
            painter.Draw(args);
            args.Cache.Dispose();
        }
  

        private void view_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Left)
            {

                GridHitInfo info;
                var pt = _view.GridControl.PointToClient(System.Windows.Forms.Control.MousePosition);
                info = _view.CalcHitInfo(pt);
                if (info.InColumn && info.InRow && _view.IsDataRow(info.RowHandle))
                    UpdateSelection();
                if (info.InColumn && info.Column == _column)
                {
                    if (SelectedCount == _view.DataRowCount)
                        ClearSelection();
                    else
                        SelectAll();
                }
                if (info.InRow && _view.IsGroupRow(info.RowHandle)
                    && info.HitTest != GridHitTest.RowGroupButton)
                {
                    bool selected = IsGroupRowSelected(info.RowHandle);
                    SelectGroup(info.RowHandle, !selected);
                }
            }
        }

        private void View_CustomDrawColumnHeader
            (object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != _column)
                return;
            e.Info.InnerElements.Clear();
            e.Painter.DrawObject(e.Info);
            //DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == _view.DataRowCount);_selection
            DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == _view.DataRowCount);
            e.Handled = true;
        }

        private void View_CustomDrawGroupRow
            (object sender, RowObjectCustomDrawEventArgs e)
        {
            var info = e.Info as GridGroupRowInfo;
            info.GroupText = "         " + info.GroupText.TrimStart();
            e.Info.Paint.FillRectangle
               (e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
            e.Painter.DrawObject(e.Info);
            var r = info.ButtonBounds;
            r.Offset(r.Width * 2, 0);
            DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle));
            e.Handled = true;
        }

        private void view_CustomUnboundColumnData
            (object sender, CustomColumnDataEventArgs e)
        {
            if (e.Column != CheckMarkColumn)
                return;
            if (e.IsGetData)
                e.Value = IsRowSelected(View.GetRowHandle(e.ListSourceRowIndex));
            else
                SelectRow(View.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
        }

        private void edit_EditValueChanged(object sender, EventArgs e)
        {
            _view.PostEditor();
        }

        private void SelectRow(int rowHandle, bool select, bool invalidate)
        {
            if (IsRowSelected(rowHandle) == select)
                return;
            object row = _view.GetRow(rowHandle);
            if (select)
                _selection.Add(row);
            else
                _selection.Remove(row);
            if (invalidate)
                Invalidate();
            OnSelectionChanged(EventArgs.Empty);
        }

        public object GetSelectedRow(int index)
        {
            return _selection[index];
        }

        public int GetSelectedIndex(object row)
        {
            return _selection.IndexOf(row);
        }
        public void ClearSelection()
        {
            _selection.Clear();
            View.ClearSelection();
            Invalidate();
            OnSelectionChanged(EventArgs.Empty);
        }

        private void Invalidate()
        {
            _view.CloseEditor();
            _view.BeginUpdate();
            _view.EndUpdate();
        }

        public void SelectAll()
        {
            _selection.Clear();
            var dataSource = _view.DataSource as ICollection;
            //if (dataSource != null && dataSource.Count == _view.DataRowCount)
            //    _selection.AddRange(dataSource);  // fast
            //else
            //    for (int i = 0; i < _view.DataRowCount; i++)  // slow
            //        _selection.Add(_view.GetRow(i));
            if (dataSource != null)
                for (int i = 0; i < _view.DataRowCount; i++)  // slow
                {
                    if ((_view.GetRow(i) as HistroyAlarmObj).statue != "已处理")
                    _selection.Add(_view.GetRow(i));
                }
                   

            Invalidate();
            OnSelectionChanged(EventArgs.Empty);
        }

        public void SelectGroup(int rowHandle, bool select)
        {
            if (IsGroupRowSelected(rowHandle) && select) return;
            for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
            {
                int childRowHandle = _view.GetChildRowHandle(rowHandle, i);
                if (_view.IsGroupRow(childRowHandle))
                    SelectGroup(childRowHandle, select);
                else
                    SelectRow(childRowHandle, select, false);
            }
            Invalidate();
        }

        public void SelectRow(int rowHandle, bool select)
        {
            SelectRow(rowHandle, select, true);
        }

        public bool IsGroupRowSelected(int rowHandle)
        {
            for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
            {
                int row = _view.GetChildRowHandle(rowHandle, i);
                if (_view.IsGroupRow(row))
                    if (!IsGroupRowSelected(row))
                        return false;
                    else
                        if (!IsRowSelected(row))
                            return false;
            }
            return true;
        }

        public bool IsRowSelected(int rowHandle)
        {
            if (_view.IsGroupRow(rowHandle))
                return IsGroupRowSelected(rowHandle);
            object row = _view.GetRow(rowHandle);
            return GetSelectedIndex(row) != -1;
        }

        public void UpdateSelection()
        {
            //_selection.Clear();
            Array.ForEach(View.GetSelectedRows(), item => SelectRow(item, true));
        }
    }
}